import { reqCartList, reqDeleteCartById, reqUpdateCheckedById } from "@/api/index"
// import { reject } from "core-js/fn/promise";

const actions = {
    //获取购物车列表数据
    async getCartList({ commit }) {
        let result = await reqCartList()
        console.log(result);
        if (result.code == 200) {
            commit('GETCARTLIST', result.data)
        }
    },
    //删除购物车某个产品
    async deleteCartListBySkuId({ commit }, skuId) {
        let result = await reqDeleteCartById(skuId)
        console.log(result);
        if (result.code == 200) {
            return 'ok'
        }
        else {
            return Promise.reject(new Error('faile'))
        }
    },
    //修改购物车某个商品的选中状态
    async updateCartListById({ commit }, { skuId, isChecked }) {
        let result = await reqUpdateCheckedById(skuId, isChecked)
        if (result.code == 200) {
            return "ok"
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //删除全部选中的产品
    deleteAllCheckcedCart({ dispatch, getters }) {
        // console.log(getters.cartList.cartInfoList);
        //获取购物车中全部产品的是一个数组
        let PromiseAll = []
        getters.cartList.cartInfoList.forEach(item => {
            if (item.isChecked == 1) {
                let promisr = dispatch('deleteCartListBySkuId', item.skuId)
                //将每一次返回的promsie添加到数组中
                PromiseAll.push(promisr)
            }
        });
        //只要全部的p1 | p2 都成功，返回结果为成功
        //如果有一个失败，返回即为失败结果
        return Promise.all(PromiseAll)
    },
    //修改全选按钮
    updateAllCartChecked({ dispatch, state }, isChecked) {
        let PromiseAll = []
        //数组
        state.cartList[0].cartInfoList.forEach(item => {
            let promise = dispatch('updateCartListById', {
                skuId: item.skuId, isChecked
            })
            PromiseAll.push(promise)
        })
        //最终返回结果
        return Promise.all(PromiseAll)
    }
};
const mutations = {
    GETCARTLIST(state, value) {
        state.cartList = value
    }
};
const state = {
    cartList: []
};
const getters = {
    cartList(state) {
        return state.cartList[0] || {}
    }
};

export default {
    actions,
    mutations,
    state,
    getters
}